﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using Film8.DAL;
using Film8.Models;

namespace Film8.Controllers
{
    [Authorize]
    public class DirectorController : Controller
    {
        private Film8Context db = new Film8Context();

        // GET: Director
        public ActionResult Index(string searchString, string searchStringID,string searchStringMovieTitle)
        {
            var directors = from s in db.Directors
                       select s;
            if (!String.IsNullOrEmpty(searchString))
            {
                directors = directors.Where(s => s.Name.ToUpper().Contains(searchString.ToUpper()));

            }
            if (!String.IsNullOrEmpty(searchStringID))
            {
               directors = directors.Where(s => s.Id.ToString().ToUpper().Contains(searchStringID.ToUpper()));

            }
            if (!String.IsNullOrEmpty(searchStringMovieTitle))    // find director by movie title, uses "join".
            {
              
        
             var directorJoinMovie = from d in db.Directors
                                     join m in db.Movies
                                     on d.Id equals m.director.Id
                                     select new { d.Name,m.Title };

             string name = (from djm in directorJoinMovie where djm.Title.Equals(searchStringMovieTitle) select djm.Name).SingleOrDefault();




             directors = directors.Where(s => s.Name.ToString().ToUpper().Contains(name.ToUpper()));

            }

          
            

            if (Request.IsAjaxRequest())
            {
                return PartialView("_DirectorsTable", directors);
            }

            return View(directors);
        }

        // GET: Director/Details/5
        public ActionResult Details(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            Director director = db.Directors.Find(id);

            var directorJoinMovieYears = from d in db.Directors 
                                         join m in db.Movies
                                         on d.Id equals m.director.Id
                                         select new { d.Name, m.Year };
          

           
          var yearsAverage = from d in directorJoinMovieYears
                        group d by d.Name into y
                        select new
                        {
                            Name = y.Key,
                            Year = y.Average(p => p.Year)

                        };


          director.AverageMoviesYear = Convert.ToInt16((from ya in yearsAverage where ya.Name.Contains(director.Name) select ya.Year).SingleOrDefault());
           

            if (director == null)
            {
                return HttpNotFound();
            }
            return View(director);
        }

        // GET: Director/Create
        public ActionResult Create()
        {
            return View();
        }

        // POST: Director/Create
        // To protect from overposting attacks, please enable the specific properties you want to bind to, for 
        // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
         [Authorize(Users = "admin@film8.com")]
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Create([Bind(Include = "Id,Name")] Director director)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    db.Directors.Add(director);
                    db.SaveChanges();
                    return RedirectToAction("Index");
                }
            }
            catch (Exception)
            {

                ModelState.AddModelError("", "Unable to save changes. Try again, and if the problem persists see your system administrator.");
            }
           

            return View(director);
        }
         [Authorize(Users = "admin@film8.com")]
        // GET: Director/Edit/5
        public ActionResult Edit(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            Director director = db.Directors.Find(id);
            if (director == null)
            {
                return HttpNotFound();
            }
            return View(director);
        }

        // POST: Director/Edit/5
        // To protect from overposting attacks, please enable the specific properties you want to bind to, for 
        // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
         [Authorize(Users = "admin@film8.com")]
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Edit([Bind(Include = "Id,Name")] Director director)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    db.Entry(director).State = EntityState.Modified;
                    db.SaveChanges();
                    return RedirectToAction("Index");
                }
            }
            catch (Exception)
            {

                ModelState.AddModelError("", "Unable to save changes. Try again, and if the problem persists see your system administrator.");

            }
           
            return View(director);
        }
         [Authorize(Users = "admin@film8.com")]
        // GET: Director/Delete/5
        public ActionResult Delete(int? id,bool? saveChangesError=false)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            Director director = db.Directors.Find(id);
            if (director == null)
            {
                return HttpNotFound();
            }
            return View(director);
        }
         [Authorize(Users = "admin@film8.com")]
        // POST: Director/Delete/5
         [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult DeleteConfirmed(int id)
        {
            try
            {
                Director director = db.Directors.Find(id);
                db.Directors.Remove(director);
                db.SaveChanges();
                
            }
             catch(Exception)
            {
                return RedirectToAction("Delete", new { id = id, saveChangesError = true });
            }
            return RedirectToAction("Index");
        }
      
        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                db.Dispose();
            }
            base.Dispose(disposing);
        }
    }
}
